/*
 * @Descripttion: 地球-浙江
 * @Author: sujunling
 * @Date: 2025-10-30 23:53:15
 */
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"demserver/src/elevation"
)

// Config represents the application configuration
type Config struct {
	DemFiles   []string `json:"demFiles"`
	ServerPort string   `json:"serverPort"`
	LogLevel   string   `json:"logLevel"`
}

const (
	// Default port for the HTTP server
	defaultPort = "8080"

	// Path to the config file
	configFilePath = "config.json"
)

func main() {
	// Load configuration
	config, err := loadConfig(configFilePath)
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// Get port from config or use default
	port := config.ServerPort
	if port == "" {
		port = defaultPort
	}

	// Load the first DEM file from config
	if len(config.DemFiles) == 0 {
		log.Fatal("No DEM files specified in config")
	}

	demFilePath := config.DemFiles[0]

	// Get absolute path to the DEM file
	absPath, err := filepath.Abs(demFilePath)
	if err != nil {
		log.Fatalf("Failed to get absolute path for DEM file: %v", err)
	}

	// Check if the DEM file exists
	if _, err := os.Stat(absPath); os.IsNotExist(err) {
		log.Fatalf("DEM file not found at: %s", absPath)
	}

	// Load the GeoTIFF file (progress will be shown by the LoadGeoTIFF function)
	geoTiff, err := elevation.LoadGeoTIFF(absPath)
	if err != nil {
		log.Fatalf("Failed to load GeoTIFF: %v", err)
	}
	fmt.Println("GeoTIFF loaded successfully")

	// Create handler
	handler := elevation.NewHandler(geoTiff)

	// Register routes with CORS support
	http.HandleFunc("/elevation", func(w http.ResponseWriter, r *http.Request) {
		// Set CORS headers
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

		// Handle preflight OPTIONS request
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		// Call the actual handler
		handler.GetElevationHandler(w, r)
	})

	// Start server
	fmt.Printf("Starting server on port %s\n", port)
	fmt.Printf("Access the elevation API at: http://localhost:%s/elevation?lat={latitude}&lon={longitude}\n", port)

	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}

// loadConfig loads the application configuration from a JSON file
func loadConfig(filename string) (*Config, error) {
	// Open config file
	file, err := os.Open(filename)
	if err != nil {
		return nil, fmt.Errorf("failed to open config file: %v", err)
	}
	defer file.Close()

	// Decode JSON
	var config Config
	decoder := json.NewDecoder(file)
	if err := decoder.Decode(&config); err != nil {
		return nil, fmt.Errorf("failed to decode config file: %v", err)
	}

	return &config, nil
}
